import { createRouter, createWebHashHistory } from 'vue-router'
import { cookieFn } from '../utils/cookieFn'
const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import(/* webpackChunkName: "Home" */ '../views/home/Home')
  },
  {
    path: '/cartlist',
    name: 'CartList',
    component: () => import(/* webpackChunkName: "Cart" */ '../views/cartList/CartList.vue')
  },
  {
    path: '/confirmOrder/:id',
    name: 'ConfirmOrder',
    component: () => import(/* webpackChunkName: "ConfirmOrder" */ '../views/confirmOrder/ConfirmOrder.vue')
  },
  {
    path: '/order',
    name: 'Order',
    component: () => import(/* webpackChunkName: "Order" */ '../views/order/Order.vue')
  },
  {
    path: '/mymess',
    name: 'MyMess',
    component: () => import(/* webpackChunkName: "MyMess" */ '../views/myMess/MyMess.vue')
  },
  {
    path: '/mymess/mysite',
    name: 'MySite',
    component: () => import(/* webpackChunkName: "MySite" */ '../views/mySite/MySite.vue')
  },
  {
    path: '/mymess/mysite/newsite',
    name: 'NewSite',
    component: () => import(/* webpackChunkName: "NewSite" */ '../views/mySite/newsite/NewSite.vue')
  },
  {
    path: '/mymess/mysite/compileSite/:id',
    name: 'CompileSite',
    component: () => import(/* webpackChunkName: "CompileSite" */ '../views/mySite/compileSite/CompileSite.vue')
  },
  {
    path: '/shop/:id',
    name: 'Shop',
    component: () => import(/* webpackChunkName: "Shop" */ '../views/shop/Shop.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import(/* webpackChunkName: "Register" */ '../components/register/Register.vue'),
    beforeEnter (to, from, next) {
      const isLogin = cookieFn() // 判断登录cookie
      isLogin ? next({ name: 'Home' }) : next()
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "Login" */ '../components/login/Login'),
    beforeEnter (to, from, next) {
      const isLogin = cookieFn() // 判断登录cookie
      if (from.name === 'Register') {
        next()
      } else {
        isLogin ? next({ name: 'Home' }) : next()
      }
    }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const isLogin = cookieFn();// 判断登录cookie
  (isLogin || to.name === 'Register' || to.name === 'Login') ? next() : next({ name: 'Login' })
})
export default router
